<script setup>
import { useRouter } from 'vue-router'
import { ref, reactive } from 'vue'
import { teacherApi } from '@/api/teacher'
import { ElMessage } from 'element-plus'

const router = useRouter()

const teacherList = ref([])
const dialogVisible = ref(false)
const dialogTitle = ref('添加教师')
const isEdit = ref(false)
const teacherForm = reactive({
  id: '',
  userId: '',
  teaName: '',
  coursNum: 0
})

// 获取教师列表
const fetchTeacherList = async () => {
  try {
    const res = await teacherApi.getTeacherList()
    teacherList.value = res.data
  } catch (error) {
    console.error('获取教师列表失败:', error)
    ElMessage.error('获取教师列表失败')
  }
}

// 组件挂载时获取列表
fetchTeacherList()

// 显示添加对话框
const showAddDialog = () => {
  dialogTitle.value = '添加教师'
  isEdit.value = false
  Object.assign(teacherForm, { id: '', userId: '', teaName: '', coursNum: 0 })
  dialogVisible.value = true
}

// 查看教师课程
const viewCourses = (id) => {
  router.push(`/teacher/courses/${id}`)
}

// 编辑教师
const editTeacher = (id) => {
  dialogTitle.value = '编辑教师'
  isEdit.value = true
  
  // 实际项目中应该先获取教师详情
  const teacherToEdit = teacherList.value.find(t => t.id === id)
  if (teacherToEdit) {
    Object.assign(teacherForm, {...teacherToEdit})
  }
  
  dialogVisible.value = true
}

// 删除教师
const deleteTeacher = async (id) => {
  try {
    await teacherApi.deleteTeacher(id)
    ElMessage.success('删除成功')
    fetchTeacherList()
  } catch (error) {
    console.error('删除失败:', error)
    ElMessage.error('删除失败')
  }
}

// 保存教师
const saveTeacher = async () => {
  try {
    if (isEdit.value) {
      await teacherApi.updateTeacher({...teacherForm})
    } else {
      await teacherApi.saveTeacher(teacherForm)
    }
    ElMessage.success('保存成功')
    dialogVisible.value = false
    fetchTeacherList()
  } catch (error) {
    console.error('保存失败:', error)
    ElMessage.error('保存失败')
  }
}

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return '-'
  const date = new Date(dateStr)
  return `${date.getFullYear()}-${String(date.getMonth()+1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
}
</script>